﻿using DotNetCore.CAP;
using SqlSugar;
using System;
using System.Data;
using System.Threading.Tasks;

namespace Cap.Subscriber.Services
{
    public class SubscriberService : ISubscriberService, ICapSubscribe
    {
        SqlSugarClient db;
        public SubscriberService()
        {
            db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = "Data Source=localhost;initial Catalog=userdb;User ID=root;Password=123456",
                DbType = SqlSugar.DbType.MySql,//设置数据库类型
                IsAutoCloseConnection = true,//自动释放数据务，如果存在事务，在事务结束后释放
                InitKeyType = InitKeyType.Attribute //从实体特性中读取主键自增列信息
            });
        }

        [CapSubscribe("cap.services.show.time")]
        public void CheckReceivedMessage(string msg)
        {
            Console.WriteLine($"services订阅时间：{msg}");

        }

        [CapSubscribe("sample.rabbitmq.MysqlServer")]
        public async Task<bool> Insert(string msg)
        {
            Console.WriteLine($"MysqlServer订阅时间：{msg}");
            if (!string.IsNullOrEmpty(msg))
            {
                using (IDbConnection connection = db.Ado.Connection)
                {
                    var role = new Role()
                    {
                        RoleName = "哈哈",
                        Remark = "测试cap",
                        RoleType = 3,
                        IsVaild = "T",
                        IsDefault = "T",
                        CreateDate = DateTime.Now,
                        CreateUser = 1
                    };
                    return (await db.Insertable(role).ExecuteCommandAsync()) > 0;
                }
            }
            Console.WriteLine("订阅成功！----");
            return false;
        }

        [CapSubscribe("Transfer.rabbitmq.test")]
        public async Task Transfer(string msg)
        {
            await Task.Run(() =>
            {
                Console.WriteLine($"中转测试---订阅时间：{msg}");
            });
        }

    }

}

